//
//  JHMiddleWordDownloadCell.m
//  JuniRengLish_iOS
//
//  Created by 邓建 on 2019/5/8.
//  Copyright © 2019 revogi. All rights reserved.
//

#import "JHMiddleWordDownloadCell.h"
#import "JHBookItemDataModel.h"
#import "JHWordItemDataModeel.h"
#import "JHBookUnitDetailViewController.h"

@implementation JHMiddleWordDownloadCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.progressView = [[JHProgressView alloc] initWithFrame:CGRectMake(JKScreenW - 49, 5, 34, 34)];
    self.progressView.progressColor = JKMainColor;
    self.progressView.progressBackgroundColor = [UIColor groupTableViewBackgroundColor];
    self.progressView.backgroundColor = [UIColor clearColor];
    self.progressView.hidden = YES;
    [self.contentView addSubview:self.progressView];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

- (IBAction)downLoadBtnDidClick:(UIButton *)sender
{
    [self selectDownLoadAndPlayVoice];
}

- (void)selectDownLoadAndPlayVoice
{
    if ([self isExistFile])
    {
        JHBookUnitDetailViewController * detail = [JHBookUnitDetailViewController new];
        self.isBook ? (detail.bookItemModel = self.itemModel) : (detail.wordItemModel = self.wordItemModel);
        detail.bookId = self.bookid;
        [self.currentVC.navigationController pushViewController:detail animated:YES];
    }
    else
    {
        [self.currentVC jxt_showAlertWithTitle:@"温馨提示" message:@"本单元数据还未下载,是否现在下载?" appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
            alertMaker.addActionCancelTitle(@"取消").addActionDefaultTitle(@"确定");
        } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
            if (buttonIndex == 1) {
                NSString * path = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:self.bookid];
                
                if (![JHFileManger fileExistsAtPath:path]) {
                    [JHFileManger createDirectory:path];
                }
                [self downLoadUntiAllFile];
            }
        }];
    }
}

#pragma mark - 下载当前单元的所有文件
- (void)downLoadUntiAllFile
{
    //反馈正在下载状态
    self.downLoadCompleteBlock(YES);
    
    if (self.isBook)
    {
        for (int j = 0; j < self.itemModel.data.count; j ++)
        {
            JHBookItemDataModel * dataModel = self.itemModel.data[j];
            [self requestDownLoadMp3:dataModel.mp3url1 FileName:dataModel.mp3name];
//            [self requestDownLoadMp3:dataModel.mp3url1 FileName:dataModel.textfile];
        }
    }
    else
    {
        for (int j = 0; j < self.wordItemModel.data.count; j ++)
        {
            JHWordItemDataModeel * dataModel = self.wordItemModel.data[j];
            [self requestDownLoadMp3:dataModel.mp3url1 FileName:dataModel.mp3name];
//            [self requestDownLoadMp3:dataModel.mp3url1 FileName:dataModel.textfile];
        }
    }
    
    NSString * doc = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@.zip", self.bookid, self.bookid]];
    if (![JHFileManger fileExistsAtPath:doc])//是否存在zip，存在说明已经下载
    {
        NSString * path = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:self.bookid];
        //是否创建了文件夹
        if (![JHFileManger fileExistsAtPath:path])
        {
            [JHFileManger createDirectory:path];
        }
        [self downZipFile:path];
    }
}

- (void)downZipFile:(NSString *)doc
{
    NSString *urlStr = [self.txtdownloadurl substringToIndex:self.txtdownloadurl.length-1];
    NSLog(@"%@ ==  下载的地址",urlStr);
    
    [DJHttpTool downloadURL:@{@"url":urlStr, @"fileName":self.bookid} progress:^(NSProgress *downloadProgress) {
        //更新下载进度
        NSLog(@"%@----hah ---", downloadProgress);
        
    } destination:^(NSURL *targetPath) {
        NSLog(@"targetPath : %@", [targetPath path]);
        //解压文件
        ([SSZipArchive unzipFileAtPath:[targetPath path] toDestination:doc]) ? (NSLog(@"解压完成")) : (NSLog(@"解压失败"));
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - 下载单元的mp3文件
- (void)requestDownLoadMp3:(NSString *)mp3url FileName:(NSString *)mp3name
{
    NSString *urlStr = [mp3url substringToIndex:mp3url.length-1];
    [DJHttpTool downloadURL:@{@"url":[urlStr stringByAppendingPathComponent:mp3name], @"fileName":self.bookid, @"name":[mp3name stringByAppendingString:@".mp3"]} progress:^(NSProgress *downloadProgress) {
        //更新下载进度
        dispatch_async(dispatch_get_main_queue(), ^{
            self.progressView.hidden = NO;
            self.downLoadBtn.hidden = YES;
        });
        NSLog(@"%@----hah ---", downloadProgress);
        
    } destination:^(NSURL *targetPath) {
        NSLog(@"targetPath : %@", [targetPath path]);
        dispatch_async(dispatch_get_main_queue(), ^{
            self.count ++;
            self.progressView.percent = self.count / self.totalCount;
            NSLog(@">>>>>>>>>>>>>%f", self.count / self.totalCount);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.count == self.totalCount)
                {
                    [DJToast showCenterToast:@"下载完成"];
                    self.progressView.hidden = YES;
                    self.downLoadBtn.hidden = NO;
                    self.downLoadCompleteBlock(NO);
                }
            });
        });
    } failure:^(NSError *error) {
        
    }];
}

- (void)setWordItemModel:(JHWordItemModel *)wordItemModel
{
    _wordItemModel = wordItemModel;
    
    self.totalCount = self.isBook ? self.itemModel.data.count : self.wordItemModel.data.count;
    self.count = 0;
    
    if ([self isExistFile])
    {
        [self.downLoadBtn setImage:[UIImage imageNamed:@"播放"] forState:0];
    }
    else
    {
        [self.downLoadBtn setImage:[UIImage imageNamed:@"下载"] forState:0];
    }
}

- (void)setItemModel:(JHBookItemModel *)itemModel
{
    _itemModel = itemModel;
    
    self.totalCount = self.isBook ? self.itemModel.data.count : self.wordItemModel.data.count;
    self.count = 0;
    
    if ([self isExistFile])
    {
        [self.downLoadBtn setImage:[UIImage imageNamed:@"播放"] forState:0];
    }
    else
    {
        [self.downLoadBtn setImage:[UIImage imageNamed:@"下载"] forState:0];
    }
}
#pragma mark - 该单元是否下载
- (BOOL)isExistFile
{
    NSInteger count = 0;
    NSInteger totalCount = 0;
    if (self.isBook)
    {
        totalCount = _itemModel.data.count;
        for (int i = 0; i < _itemModel.data.count; i ++)
        {
            JHBookItemDataModel * model = _itemModel.data[i];
            NSString * txtFile = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", self.bookid, model.textfile]];
            NSString * mp3File = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@.mp3", self.bookid, model.mp3name]];
            if ([JHFileManger fileExistsAtPath:txtFile] && [JHFileManger fileExistsAtPath:mp3File])
            {
                count ++;
            }
        }
    }
    else
    {
        totalCount = _wordItemModel.data.count;
        for (int i = 0; i < _wordItemModel.data.count; i ++)
        {
            JHWordItemDataModeel  * model = _wordItemModel.data[i];
            NSString * txtFile = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", self.bookid, model.textfile]];
            NSString * mp3File = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@.mp3", self.bookid, model.mp3name]];
            if ([JHFileManger fileExistsAtPath:txtFile] && [JHFileManger fileExistsAtPath:mp3File])
            {
                count ++;
            }
        }
    }
    
    if (count == totalCount)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

@end
